<?php

namespace pc\controllers;
use pc\models\News;
use pc\models\Portray;
use pc\models\Star;
use pc\models\Tags;
use Yii;

use pc\controllers\BaseController;
use yii\helpers\Url;


class MeinvController extends BaseController
{

    /*
     * 示例链接
     * /meinv/taiwan-qincun-qizi-xushen-Gnai-wanghong/page-2.html
     */
    public function actionIndex()
    {
        $tags = trim(Yii::$app->request->get('tags'));
        $page = (int)Yii::$app->request->get('page') ?: 1;

        $tagModel = new Tags();
//        $tagModel->setRedis();

        $tagInfoList = $tagModel->parseTags($tags); //获取标签详情 同时干掉无效标签
        $starTagMenu = $tagModel->starTagMenu($tagInfoList); //获取美女标签菜单
        $typeName = [0 => '标签', 1 => '区域' , 2 => '类型' , 3 => '职业' , 4 => '星座'];

        //指定字段获取明星列表数据
        $needFields = ['id','name','nick_name','header','view','ranking']; //查询的字段
        $result = Star::getStarByTags($tagInfoList,$page,20,$needFields);

        $recommendStar = [];
        if($result['pagination']['totalCount'] < 10){  //結果少于10个直接推荐10个
            $recommendStar = Star::recommendStars(10,$needFields);
        }

        //设置分页数据
        $pagination = $result['pagination'];
        $tagAlias = $tagInfoList ? implode('-',array_column($tagInfoList,'alias')) : '';
        if(empty($tagAlias)){
            $pagination['formatUrl'] = '/meinv/page-{page}.html';
            $pagination['firstUrl'] = '/meinv/';
        }else{
            $pagination['formatUrl'] = '/meinv/'.$tagAlias.'/page-{page}.html';
            $pagination['firstUrl'] = '/meinv/'.$tagAlias.'/';
        }
        $pageString = $this->createPageString($pagination);

        //tdk
        $tagString = empty($tagInfoList) ? '' : implode('',array_column($tagInfoList,'name'));
        return $this->render('index',[
            'tags' => $tags,
            'menu' => $starTagMenu,
            'typeName'=>$typeName,
            'stars' => $result['data'],
            'recommendStar' => $recommendStar,
            'pageString' => $pageString,
            'page' => $page,
            'tagsInfo' => $tagInfoList,
            'tagString' => $tagString
        ]);
    }


    public function actionInfo(){
        $starId = (int)Yii::$app->request->get('id');
        $starInfo = Star::getStarInfoById($starId);
        //相关新闻 相关写真 推荐写真 明星总榜
        if(!$starInfo){
            //TODO 404
        }

        //添加浏览量
        Star::incrView($starId);
        //明星相关新闻
        $relationNews = News::getStarNews(4,['id','image','title','desc','create_time','view']);
        //右侧明星总榜
        $stars = Star::getMaxViewStar(1,5,['id','name','nick_name','view','header'])['data'];
        //明星属性
        $attrString = $this->createAttrString($starInfo);
        //相关写真
        $portrays = Portray::getStarAllPortrays($starId,['id','title']);
        //推荐写真数据
        $recommendPortrays = Portray::recommendPortrays(4);
        //热门女星
        $recommendStars = Star::recommendStars(4,['id','name','nick_name','header']);

        return $this->render('info',[
            'star' => $starInfo,
            'stars' => $stars,
            'news' => $relationNews,
            'attrString' => $attrString,
            'portrays' => $portrays,
            'recommendPortrays' => $recommendPortrays,
            'recommendStars' => $recommendStars
        ]);
    }

    public function actionAjax($action = ''){
        $actions = ['change-stars','change-portrays'];
        if(!Yii::$app->request->isAjax || !in_array($action,$actions)){
            $this->redirect(Url::to('/meinv/'));
        }

        $this->layout = false;
        if($action == 'change-stars'){
            $recommendStars = Star::recommendStars(4,['id','name','nick_name','header']);
            return $this->render('recommendStar',[
                'recommendStars' => $recommendStars
            ]);
        }

        if($action == 'change-portrays'){
            $recommendPortrays = Portray::recommendPortrays(4);
            return $this->render('recommendPortray',[
                'recommendPortrays' => $recommendPortrays,
            ]);
        }

    }

    //动态生成明星属性标签
    private function createAttrString($starInfo){
        $attributes = ['birth_place','birthday','interest','star_sign','size','height','weight','blood_type','animal','job','country']; //,'interest','job'
        $model = new Star();
        $attributeLabels  = $model->attributeLabels();

        $count = 0;
        $str = '<p>';

        $allAuto = false;
        foreach($attributes as $attr){
            if($starInfo[$attr]){
                if($attr == 'country') continue;
                $count++;

                $width = in_array($attr,['interest','job']) ? 'style="width:auto;"' : '';
                if($allAuto === false && mb_strlen($starInfo[$attr]) > 11){
                    $allAuto = true;
                }
                $str .= "<span {$width} ><label>{$attributeLabels[$attr]}：</label>";

                if(in_array($attr,['birth_place','job','interest','tags'])){
                    $tags = $attr == 'birth_place' ? Tags::parseTagsByName($starInfo['country']) : Tags::parseTagsByName($starInfo[$attr]);

                    if($tags){
                        $tmp  = $attr == 'birth_place' ? $starInfo['country'] : '';
                        $tmp .= $starInfo[$attr];
                        foreach ($tags as $tagInfo){
                            $tmp = str_replace($tagInfo['name'],"<a style='color:#f69;' href='/meinv/{$tagInfo['alias']}/' title ='{$tagInfo['name']}美女'>{$tagInfo['name']}</a>",$tmp);
                        }
                        $str .= $tmp;
                        unset($tmp);
                    }else{
                        $str .= $starInfo[$attr];
                    }
                }elseif($attr == 'star_sign'){
                    $str .= "<a style='color:#f69;' target='_blank' href='/meinv/".Yii::$app->params['starSignAlias'][$starInfo[$attr]]."/' title ='".Yii::$app->params['starSign'][$starInfo[$attr]]."美女'>".Yii::$app->params['starSign'][$starInfo[$attr]]."</a>";
                }elseif ($attr == 'birthday'){
                    $str .= date('Y年m月d日',$starInfo[$attr]);
                }else{
                    $str .= $starInfo[$attr];
                }
                $attr == 'height' && $str .= 'CM';
                $attr == 'weight' && $str .= 'KG';
                $attr == 'blood_type' && $str .= '型';

                $str .= '</span>';
                if($count % 3 == 0) $str .= '</p><p>';
            }
        }
        $str .= '</p>';
        if($count < 3) $str = str_replace('<p>','<p style="line-height: 89px;">',$str);
        if($count > 3 && $count < 7) $str = str_replace('<p>','<p style="line-height: 46px;">',$str);
        if($allAuto){
            $str = str_replace('style="width:auto;"','',$str);
            $str = str_replace('<span ','<span style="width:auto;" ',$str);
        }
        return $str;
    }


    public function actionSetRedis(){
       $model = New Star();
       $model->setStarRedis();
//       $model->analysisStar();
    }

    public function actionFenci(){
        $model = new Star();
//        $model->setStarRedis();
    }


    public function actionDealTag(){
        $model = new Tags();
        $model->relationGirl(); //一步到位

        //$model->dealJobTags();
//        $model->updateTagSort();

    }

}
